package aop;

import entity.Admin;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  登录拦截器
 * @author bigpeng
 * @create 2020-06-09-16:55
 */
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 在控制层方法请求之前调用，返回一个boolean类型值
     * 如果返回的true则放行，如果返回false，则不继续往后执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        System.out.println("拦截到请求："+requestURI);
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        //如果admin为空，说明没有登录
        if(admin==null){
          response.sendRedirect(request.getContextPath()+"/login.jsp");
          return false;//不继续往后执行
        }
        return true;
    }

    /**
     * 在控制层方法执行放回之后执行，通常可以做一些全局的数据返回等
     * @param modelAndView 控制层方法返回的结果
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("进入拦截器postHandle方法");
        //ajax请求时，modelAndView为null
        if(modelAndView!=null) {
            System.out.println("获取到控制层方法返回结果：" + modelAndView.getModelMap()
                    + "view:" + modelAndView.getViewName());
        }
    }
    /**
     *  视图解析之后执行，通常用来做一些清理工作
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("进入afterCompletion方法");
    }
}
